<template>
    <div class="layout">
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="12"
                :group-id="group_id"
                :auth-code="authCode"
                @submit="handleGroupSubmit"></ZWGroup>
            <div class="container_right">
                <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset"></ZwSearchForm>
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :option="tableOption"
                    :row-key="getRowKey"
                    :fetch-params="state.searchParams"
                    :fetch-api="fetchApi()"
                    :close-loading="true"
                    @select="onSelect"
                    @selection-change="onSelectionChange"
                    @select-all="onSelectAll">
                    <template #headerOperate>
                        <el-button v-auth="'BATCH_DOW'" :disabled="!checkList.length" class="btn" @click="batchDwon">
                            批量下载
                        </el-button>
                        <el-button v-auth="'BATCH_DEL'" :disabled="!checkList.length" class="btn" @click="batchDels">
                            批量删除
                        </el-button>
                        <el-button v-auth="'BATCH_END'" :disabled="!checkList.length" class="btn" @click="batchEnds">
                            批量结束
                        </el-button>
                        <el-button v-auth="'NEW_CODE'" class="primary" type="primary" @click="newLiveCode">
                            新建活码
                        </el-button>
                    </template>
                </ZwTable>
            </div>
        </div>
        <CustomerDetails ref="CustomerDetailsRef"></CustomerDetails>
        <Dialog :app-dialog="appDialog">
            <div class="msg">
                {{ message }}
            </div>
        </Dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
import { endLoading, startLoading } from '@/utils/request';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWGroup from '@/components/ZWGroup.vue';
import useClipboard from 'vue-clipboard3';
import CustomerDetails from './components/CustomerDetails.vue';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import {
    groupCodeList,
    groupBatchDow,
    groupBatchDel,
    groupBatchEnd,
    groupStartOrEnd
} from '@/api/smartMarketing/drainage/channelCode/index';
import { downloadByBlob } from '@/utils/utils';
import { ref, reactive, computed, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { getCreateList } from '@/api/common';
import { StatusColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { isCachePage } from '@/utils/utils';
import { useStore } from '@/store';
import Dialog from '@/components/Dialog.vue';
const store = useStore();
const DeletdialogRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const GroupingRef = ref();
const isShow = ref(0);
const checkList = ref([]);
const delId = ref([]);
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const group_id = ref<string | number>('all');

const { toClipboard } = useClipboard();

const defaultParams = {
    group_id: 'all',
    name: '', //活动标题
    user_id: [], //创建人id
    activity_status: 0, //活动状态 0-全部 1-未开始 2-进行中 3-已结束 4-提前结束
    create_time: [] //创建时间
};

// 分组权限code码
const authCode = {
    add: 'ADD_CHILD_CODE',
    edit: 'EDIT_GROUP_CODE',
    del: 'DEL_CHILD_GROUP'
};
const handleGroupSubmit = (v: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupCode',
        query: { group_id: v.id }
    });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value?.clearSelection();
    // route.query.group_id = v.id;
};

const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '活码搜索',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '输入活码标题进行搜索',
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        //   },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '活码状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            optionList: [
                { name: '全部', id: 0 },
                { name: '未开始', id: 1 },
                { name: '进行中', id: 2 },
                { name: '已结束', id: 3 },
                { name: '提前结束', id: 4 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), ...v, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        minWidth: 200,
        fixed: 'left'
    },
    {
        prop: 'qr_code_link',
        label: '二维码',
        minWidth: 100,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        src={row.qr_code_link}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        prop: 'group_name',
        label: '使用群',
        width: 200,
        render({ row, column, index }: any) {
            if (row.groupchat.length <= 3) {
                return (
                    <div>
                        {row.groupchat.map((item: any, index: number) => {
                            return (
                                <span>
                                    {item}
                                    <span v-show={row.groupchat.length - 1 != index}>、</span>{' '}
                                </span>
                            );
                        })}
                    </div>
                );
            } else {
                return (
                    <>
                        {row.groupchat[0]}等 <span style="color: #ff6b00"> {row.groupchat.length} </span>个群聊
                    </>
                );
            }
        }
    },
    {
        prop: 'scan_num',
        label: '扫码进群人数',
        width: 180
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 150
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 200
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200
    },
    {
        prop: 'effective_time',
        label: '活动有效期',
        width: 350,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <span>{row.begin_date}</span>
                            <span>至</span>
                            <span>{row.end_date}</span>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'activity_status',
        label: '状态',
        width: 100,
        render({ row, column, index }) {
            const activity_status_option = {
                '1': '未开始',
                '2': '进行中',
                '3': '已结束',
                '4': '提前结束'
            };
            return (
                <div
                    style={`color: ${
                        row.activity_status == 2 ? '#59d2a0' : row.activity_status == 4 ? '#fe292b' : ''
                    } `}>
                    {activity_status_option[row.activity_status]}
                </div>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '客户明细',
                authCode: 'GUEST_DETAIL',
                click: (row: any) => CustomerDetailsRef.value.check(row),
                isRender: ({ row }: any) => [1, 2, 3, 4].includes(row.activity_status)
            },
            {
                name: '查看',
                authCode: 'LOOK_CODE',
                click: (row: any) => look(row),
                isRender: ({ row }: any) => [1, 2, 3, 4].includes(row.activity_status)
            },
            {
                name: '编辑',
                authCode: 'EDIT',
                click: (row: any) => edit(row),
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status)
            },
            {
                name: '开始',
                authCode: 'END_CODE',
                click: (row: any) => start(row),
                isRender: ({ row }: any) => [1].includes(row.activity_status)
            },
            {
                name: '结束',
                authCode: 'END_CODE',
                click: (row: any) => finish(row),
                isRender: ({ row }: any) => row.activity_status !== 4 || row.activity_status === 2
            },
            {
                name: '下载',
                authCode: 'DOW_CODE',
                click: (row: any) => downloads(row),
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status)
            },
            {
                name: '统计',
                authCode: 'GROUP_STAT',
                click: (row: any) => goStat(row),
                isRender: ({ row }: any) => row.activity_status !== 1
            },
            {
                name: '删除',
                authCode: 'DEL_CODE',
                click: (row: any) => del(row),
                isRender: ({ row }: any) => row.activity_status !== 1
            },
            {
                name: '复制',
                click: (row: any) => copy(row),
                isRender: ({ row }: any) => Boolean(row.activity_url)
            }
        ]
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const dataId = ref();
// 查看
const look = (data: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupCode/newCode',
        query: { type: 'look', id: data.id }
    });
};
//编辑
const edit = (data: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupCode/newCode',
        query: { type: 'edit', id: data.id }
    });
};
// 开始
const start = (data: any) => {
    const res = { activity_id: data.id, status: 1 };
    groupStartOrEnd(res)
        .then((res: any) => {
            tableRef.value?.clearSelection();
            reloadTable();
            ElMessage.success('开始成功');
        })
        .catch((err: any) => {
            ElMessage.error('开始失败');
        });
};
// 统计
const goStat = (row: any) => {
    router.push({
        path: '/smartMarketing/drainage/groupCode/stat',
        query: { id: row.id }
    });
};
// 结束
const finish = (data: any) => {
    dataId.value = data.id;
    batchType.value = 3;
    title.value = '结束';
    message.value = '结束活码不可再次扫码添加';
    appDialog.visible = true;
};
// 删除
const del = async (data: any) => {
    title.value = '删除';
    batchType.value = 4;
    dataId.value = data.id;
    message.value = '确定要删除吗？';
    appDialog.visible = true;
};
// 复制
const copy = async (data: any) => {
    try {
        await toClipboard(data.activity_url);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
// 下载
const downloads = (data: any) => {
    const params = { activity_id: [data.id] };
    groupBatchDow(params)
        .then((res: any) => {
            downloadByBlob(res.url.url, res.url.name);
            // tableRef.value?.clearSelection();
        })
        .catch((e: any) => {
            ElMessage.error('下载失败');
        });
};
const fetchApi = () => {
    return groupCodeList;
};

const CustomerDetailsRef = ref();
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 导出表格数据
const exportTableData = () => {};

const title = ref(); // 弹框标题
const message = ref(); // 弹框提示信息
const batchType = ref(); //弹框类型
// 弹框取消
const cancelHandel = () => {
    appDialog.visible = false;
    batchType.value = '';
};
// 弹框确认
const submitHandel = async () => {
    startLoading();
    const params = {
        activity_id: checkList.value
    };
    if (batchType.value === 1) {
        groupBatchDel(params)
            .then((res: any) => {
                ElMessage.success('批量删除成功');
                tableRef.value?.clearSelection();
                GroupingRef.value.getGroup(12);
                reloadTable();
                cancelHandel();
            })
            .catch((err: any) => {
                // ElMessage.error('批量删除失败');
                cancelHandel();
                endLoading();
            });
    } else if (batchType.value === 2) {
        groupBatchEnd(params)
            .then((res: any) => {
                ElMessage.success('批量结束成功');
                tableRef.value?.clearSelection();
                reloadTable();
                cancelHandel();
            })
            .catch((err: any) => {
                // ElMessage.error('批量结束失败');
                cancelHandel();
                endLoading();
            });
    } else if (batchType.value === 3) {
        const result = { activity_id: dataId.value, status: 2 };
        groupStartOrEnd(result)
            .then((res: any) => {
                appDialog.visible = false;
                tableRef.value?.clearSelection();
                reloadTable();
            })
            .catch((e: any) => {
                endLoading();
            });
    } else if (batchType.value === 4) {
        const result = {
            activity_id: [dataId.value]
        };
        groupBatchDel(result)
            .then((res: any) => {
                tableRef.value?.clearSelection();
                GroupingRef.value.getGroup(12);
                reloadTable();
                ElMessage.success('删除成功');
                cancelHandel();
            })
            .catch((err: any) => {
                cancelHandel();
                // ElMessage.success('删除失败');
                endLoading();
            });
    }

    // state.searchParams = deepCopy(currentParams.value)
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: title,
    width: '460px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
// 新增收集表
const newLiveCode = () => {
    router.push({
        path: '/smartMarketing/drainage/groupCode/newCode',
        query: { type: 'new', group_id: group_id.value == 'all' ? '0' : group_id.value }
    });
};
// 批量下载
const batchDwon = () => {
    const params = { activity_id: checkList.value };
    groupBatchDow(params)
        .then((res: any) => {
            ElMessage.success('下载成功');
            const type = res.url.name.match(/\.([^\.]+)$/)[1];
            type == 'zip' ? DOWLOAD_FILE(res.url.url, res.url.name) : downloadByBlob(res.url.url, res.url.name);
            tableRef.value?.clearSelection();
        })
        .catch((e: any) => {
            ElMessage.error('下载失败');
        });
};
// 批量删除
const batchDels = () => {
    batchType.value = 1;
    title.value = '批量删除';
    message.value = '确定要批量删除吗？';
    appDialog.visible = true;
};
// 批量结束
const batchEnds = () => {
    batchType.value = 2;
    title.value = '批量结束';
    message.value = '结束后活码将失效,是否继续？';
    appDialog.visible = true;
};
onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(12);
        }
        tableRef.value.clearSelection();
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
        requestFlag.value = true;
    }
});
</script>

<style lang="scss" scoped>
.layout {
    .container {
        display: flex;

        .container_right {
            flex: 1;
            padding: 24px;
            box-sizing: border-box;
            background: #fff;
            border: 1px solid #eaeaea;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 142px);
            overflow: hidden;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

.msg {
    text-align: center;
    padding: 50px 0;
}
</style>
